package servlet;

import dao.BlogDao;
import dao.UserDao;
import model.Blog;
import model.User;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    public BlogDao blogDao = new BlogDao();
    public UserDao userDao = new UserDao();

    /**
     * 获得个人主页信息
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //博客列表页, 返回登录用户信息
        //登录用户信息,从session里面去拿
        //博客详情页, 返回作者的信息
        //作者的信息, 根据blogId 去查
        resp.setCharacterEncoding("utf-8");
        //获取用户登录信息
        HttpSession session = req.getSession(false);
        if (session ==null || session.getAttribute("user")==null){
            resp.getWriter().write("用户未登录");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user==null || user.getId()<=0){
            resp.getWriter().write("用户未登录");
            return;
        }

        String blogIdParam = req.getParameter("blogId");
        //博客列表页
        if (blogIdParam ==null || "".equals(blogIdParam)){
            //返回用户登录信息
            resp.setContentType("application/json;");
            resp.getWriter().write(JSONUtil.toJson(user));
        }else {
            //博客详情页
            Integer blogId = Integer.parseInt(blogIdParam);
            Blog blog = blogDao.selectById(blogId);
            //拿到作者信息
            User author = userDao.selectById(blog.getUserId());

            //判断当前登录用户是否和作者是同一个人
            if (author.getId() == user.getId()){
                author.setIsYourBlog(1);
            }

            resp.setContentType("application/json;");
            resp.getWriter().write(JSONUtil.toJson(author));
        }
    }
